<?php
require_once dirname(__FILE__) . '/../common.inc.php';

header('Content-Type: text/plain');

$myPdo = DbUtils::createPdoInst();

$action = MiscUtils::getParam('action', NULL);
try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'knowledgebases':
      knowledgebases($myPdo);
      break;
    case 'deleteknowledge':
      deleteknowledge($myPdo);
      break;
    case 'delete':
      delete($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  echo ERROR_SIGN . $e->getMessage();
}

function knowledgebases($myPdo) {
  $q = json_decode(MiscUtils::getParam('q', '[]'));
  $page = ($q[0]->page) ? $q[0]->page : 1;
  $size = ($q[0]->size) ? $q[0]->size : SIZE;
  $type = ($q[0]->type) ? $q[0]->type : '';
  
  if ($type != '') {
	  $cond_vals = new stdClass();
	  $cond_vals->c = 't.type = :v1';
	  $cond_vals->v = array(':v1' => $q[0]->type);
	  $result = DbUtils::get(DbUtils::createPdoInst(), 'pz_knowledge', $cond_vals, NULL, NULL, $page, $size, NULL);
  } else {
    $result = DbUtils::get(DbUtils::createPdoInst(), 'pz_knowledge', NULL, NULL, NULL, $page, $size, NULL);
  }
  echo json_encode($result);
}


function deleteknowledge($myPdo) {
  $q = json_decode(MiscUtils::getParam('q', '[]'));
  foreach ($q as &$tmp) {
	  if (file_exists($tmp->link)) {
	    unlink($tmp->link);
	  }
	  $cond_vals = new stdClass();
	  $cond_vals->c = 'id = ?';
	  $cond_vals->v = array($tmp->id);
	  DbUtils::deleteByCond($myPdo, 'pz_knowledge', $cond_vals);
	  
	  $cond_vals1 = new stdClass();
    $cond_vals1->c = 'knowledge_trackId = ?';
    $cond_vals1->v = array($tmp->track_id);
    DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_CUSTOM . 'knowledge' . '_image', $cond_vals1);
  }
  echo json_encode(array());
}

function delete($myPdo) {
  $q = json_decode(MiscUtils::getParam('q', '[]'));
  if (file_exists($q->link)) {
    unlink($q->link);
  }
  $cond_vals = new stdClass();
  $cond_vals->c = 'track_id = ?';
  $cond_vals->v = array($q->track_id);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_CUSTOM . 'knowledge' . '_image', $cond_vals);
  echo json_encode(array());
}
?>